//
//  CustomTabItem.m
//
//
//  Created by zhangtie on 13-4-3.
//  Copyright (c) 2013年 zhangtie. All rights reserved.
//

#import "CustomTabModel.h"

@implementation CustomTabItem_DataItem

@synthesize key_data = _key_data;

@end

@implementation CustomTabItem

@synthesize state = _state, tabItem_delegate = _delegate, color_normal = _color_normal, color_selected = _color_selected, nindex = _nindex;

- (void)dealloc
{
    RELEASE_SAFELY(_color_normal);
    RELEASE_SAFELY(_color_selected);
    RELEASE_SAFELY(_color_textNormal);
    RELEASE_SAFELY(_color_textSelected);
    RELEASE_SAFELY(_lab_title);
    _delegate = nil;
    RELEASE_SAFELY(_background);
    RELEASE_SAFELY(_bg_background);
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        // Initialization code
        _lab_title = nil;
        
        _color_textSelected = nil;
        _color_textNormal   = nil;
        _color_normal       = nil;
        _color_selected     = nil;
        _bg_background      = nil;
        _background         = nil;

        //添加点击手势
        UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doTap:)];
        tap.numberOfTapsRequired = 1;
        [self addGestureRecognizer:tap];
        RELEASE_SAFELY(tap);
    }
    return self;
}

/**
 descrtion:修改item状态, 这里会根据state修改对应的背景色
 @parm: _state:目标状态
 @returns:
 add by zt 2013-4-3
 @exception:
 */
- (void)changeForState:(TABITEM_STATE)state
{
    _state = state;
    
    if([[self title] isEqualToString:@"默认"])
    {
        UIImage *img_default = IMGNAMED(@"bg_condition_default.png");
        CGRect bg_frame = self.background.frame;
        //            bg_frame.size = img_default.size;
        bg_frame.origin.x = (self.frame.size.width - img_default.size.width)/2;
        bg_frame.size = img_default.size;
        self.background.frame = bg_frame;
        [self bringSubviewToFront:_lab_title];
        [self.background setImage:IMGNAMED(@"bg_condition_default.png")];
        return;
    }
    
    
    if(_state == TABITEM_STATE_SELECTED)//选中
    {
        if(!_background.image)
        {
            [_lab_title setBackgroundColor:_color_selected];
        }
        else
        {//有背景图片则去除背景色
            [_lab_title setBackgroundColor:[UIColor colorWithPatternImage:_background.image]];
//            [_lab_title setBackgroundColor:[UIColor whiteColor]];
        }
        [_lab_title setTextColor:_color_textSelected];
        [self bringSubviewToFront:_lab_title];
    }
    else
    {
        if(!_background.image)
            [_lab_title setBackgroundColor:_color_normal];
        else
        {//有背景图片则去除背景色
            [_lab_title setBackgroundColor:[UIColor colorWithPatternImage:_background.image]];
        }
        [_lab_title setTextColor:_color_textNormal];
        [self bringSubviewToFront:_lab_title];
    }
    
}

- (void)doTap:(UITapGestureRecognizer*)ges
{//交给上层视图处理
    if(_delegate && [_delegate respondsToSelector:@selector(doTabItemClick:)])
        [_delegate performSelector:@selector(doTabItemClick:) withObject:self];
    
}

/**
 descrtion: 设置索引
 @parm: _index:设置的index
 @returns:
 add by zt 2013-4-3
 @exception:
 */
- (void)setIndex:(NSInteger)index
{
    _nindex = index;
}

/**
 descrtion:初始化label,默认字号和对齐方式
 @parm:
 @returns:
 add by zt 2013-4-3
 @exception:
 */
- (UILabel*)createTitleLabel
{
    if(!_lab_title)
    {
        CGRect lab_frame = self.bounds;
        CGFloat lab_paddingBottom = ITEM_PADDINGBOTTOM;
        //    CGFloat lab_paddingRight  = ITEM_PADDINTLEFT;
        lab_frame.origin.x = _item_horizon_margin;
        lab_frame.size.width  = floorf(lab_frame.size.width - lab_frame.origin.x*2);
        lab_frame.size.height = floorf(lab_frame.size.height - lab_paddingBottom);
        _lab_title = _ALLOC_OBJ_WITHFRAME_(UILabel, lab_frame);
        [_lab_title setBackgroundColor:[UIColor clearColor]];
        [_lab_title setTextAlignment:ALIGN_CENTER];
        [_lab_title setFont:FONT_DEFAULT];
    }
    return _lab_title;
    //    SIMPLE_SAFERELEASE(_lab_title);
}

- (NSString*)title
{
    return _lab_title.text;
}

/**
 descrtion:设置title
 @parm: str_title:要显示的title
 @returns:
 add by zt 2013-4-3
 @exception:
 */
- (void)setTabItemTitle:(NSString*)str_title
{
    if(!str_title)
        return;
    
    if(!_lab_title)
        [self addSubview:[self createTitleLabel]];
    
    [_lab_title setText:str_title];
}

/**
 descrtion:设置字体
 @parm: font_size:要显示的字号大小
 @returns:
 add by zt 2013-4-3
 @exception:
 */
- (void)setFontSize:(CGFloat)font_size
{
    if(!_lab_title)
        [self addSubview:[self createTitleLabel]];
    
    [_lab_title setFont:FONT_TITLE(font_size)];
}

/**
 descrtion:设置对齐方式
 @parm: align:目标对齐方式
 @returns:
 add by zt 2013-4-3
 @exception:
 */
- (void)setAlign:(NSUITextAlignment)align
{
    if(!_lab_title)
        [self addSubview:[self createTitleLabel]];
    
    [_lab_title setTextAlignment:align];
}

- (UIImageView*)background
{
    if(!_bg_background)
    {
        [self addSubview:[self createBgView]];
    }
    
    if(!_background)
    {
        _background = _ALLOC_OBJ_WITHFRAME_(UIImageView, self.bounds);
        [_bg_background addSubview:_background];
    }
    
    return _background;
}

- (UIView*)createBgView
{
    if(!_bg_background)
    {
        CGRect bg_frame = self.bounds;
        _bg_background = _ALLOC_OBJ_WITHFRAME_(UIView, bg_frame);
        [_bg_background setBackgroundColor:[UIColor clearColor]];
    }
    return _bg_background;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
// - (void)drawRect:(CGRect)rect
// {
// // Drawing code
////     [super drawRect:rect];
//     UIColor *bg_color = (_state == TABITEM_STATE_NORMAL)?_color_normal:_color_selected;
//     [self setBackgroundColor:bg_color];
// }


@end


#pragma mark -- CustomTabList

//默认布局方式(均分)
@interface CustomTabList (defaultLayout)

- (void)defaultLayoutForDataSource:(NSMutableArray*)dataSource;

@end

@implementation CustomTabList

@synthesize layout_type = _layout_type, tabList_delegate = _delegate, ndefaultSelectedIndex = _ndefaultSelectedIndex, dataSource = _dataSource;

-(void)dealloc
{
//    [self removeObserver:self forKeyPath:@"dataSource"];
    RELEASE_SAFELY(_dataSource);
    RELEASE_SAFELY(_view_scroll);
    RELEASE_SAFELY(_imageSign);
    RELEASE_SAFELY(_imageNoteSign);
    RELEASE_SAFELY(_container);
    [super dealloc];
}

- (id)init
{
    return [self initWithFrame:CGRectZero];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self)
    {
        [self setBackgroundColor:[UIColor whiteColor]];
        //设置默认值
        _layout_type = LAYOUT_TYPE_DEFAULT;
        _ndefaultSelectedIndex = 0;
        _isCoverage = YES;
        _isNeedDefaultSelectedEvent = YES;
        _padding_top = 0;
        _font_size = 0;
        _padding_right = 0;
        _padding_bottom = ITEM_PADDINGBOTTOM;
        _item_horizon_margin = ITEM_PADDINTLEFT;
        //注册数据源监听
//        [self addObserver:self forKeyPath:@"dataSource" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
    }
    return self;
}

/**
 descrtion:初始化容器对象
 add by zt 2013-4-3
 @exception:
 */
-(void)initContainer
{
    if(!_container)
        _container = _ALLOC_OBJ_(NSMutableArray);
    else
        [_container removeAllObjects];
}

- (void)initScrollView
{
    if(_view_scroll)
    {
        [_view_scroll removeFromSuperview];
        _view_scroll = nil;
    }
    
    CGRect scroll_frame = self.bounds;
    scroll_frame.size.width -= _padding_right;
    _view_scroll = _ALLOC_OBJ_WITHFRAME_(UIScrollView, scroll_frame);
    _view_scroll.delegate = self;
    _view_scroll.showsHorizontalScrollIndicator = NO;
    [self addSubview:_view_scroll];
    //    SIMPLE_SAFERELEASE(_view_scroll);
    
}

- (void)initImageSign
{
    if(!_imageSign)
    {
        _imageSign = [[UIImageView alloc]initWithImage:IMGNAMED(@"graysign.png")];
        
        //        SIMPLE_SAFERELEASE(_imageSign);
    }
    [_view_scroll addSubview:_imageSign];
}

- (void)initNoteImageSign
{
    if(!_imageNoteSign)
    {
        _imageNoteSign = [[UIImageView alloc]initWithFrame:CGRectZero];
        
        //        SIMPLE_SAFERELEASE(_imageSign);
    }
    [self addSubview:_imageNoteSign];
}

- (void)setNoteImageSignForNoteType:(NOTE_TYPE)note_type
{
    NSString *str_img = (note_type == NOTE_TYPE_LEFT)?[@"note_left_sign.png" retain]:[@"note_right_sign.png" retain];
    UIImage *image = IMGNAMED(str_img);
    RELEASE_SAFELY(str_img);
    CGFloat width = image.size.width;
    CGFloat height = image.size.height;
    CGFloat orginX = self.frame.size.width - width - 1;
    CGFloat orginY = (self.frame.size.height - height)/2;
    CGRect noteSign_frame = CGRectMake(orginX, orginY, width, height);
    if(!_imageNoteSign)
    {
        [self initNoteImageSign];
    }
    else
        [self addSubview:_imageNoteSign];
    _imageNoteSign.frame = noteSign_frame;
    
    _imageNoteSign.image = image;
    [self bringSubviewToFront:_imageNoteSign];
}


- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    
    REMOVEALLSUBVIEW(self);
    
    if(!_dataSource || [_dataSource count]<=0)
        return;
    
    
    _view_scroll = nil;
    
    //初始化容器
    [self initContainer];
    
    [self initScrollView];
    
    //采用默认布局，这里可以扩充
    if(_layout_type == LAYOUT_TYPE_DEFAULT)
        [self defaultLayoutForDataSource:_dataSource];
    else if(_layout_type == LAYOUT_TYPE_SIGNIMAGE)
        [self signImageLayout:_dataSource];
    
    
}

/**
 descrtion:获取某个item标题
 @parm: item:要获取标题的item
 @returns:返回参数item的标题
 add by zt 2013-4-3
 @exception:
 */
- (NSString*)getTitleForItem:(CustomTabItem_DataItem*)item
{
    if(!item)
        return @"";
    
    if(item.data_type == DATA_TYPE_VALUE)
        return item.item_data;
    else
    {
        if(item.key_data)
        {
            if(item.item_data && [item.item_data count]>0)
                return [item.item_data objectForKey:item.key_data];
        }
    }
    return @"";
}

- (void)setItemSelected:(CustomTabItem*)item
{
    CGRect bg_frame = item.bounds;
    item.background.frame = bg_frame;
    item.background.image = _bgimage_selected;
    UIColor *bgColor = (self.bgimage_normal)?[UIColor colorWithPatternImage:self.bgimage_normal]:self.color_normal;
    item.bg_background.backgroundColor = bgColor;
    
}

- (void)setItemNormal:(CustomTabItem*)item withPaddingBottom:(CGFloat)bottom
{
    CGRect bg_frame = item.bounds;
    bg_frame.size.height -= bottom;
    item.background.frame = bg_frame;
    item.background.image = _bgimage_normal;
//    item.background.backgroundColor = [UIColor clearColor];
    item.bg_background.backgroundColor = [UIColor clearColor];
    //    UIColor *bgColor = (self.bgimage_normal)?[UIColor colorWithPatternImage:self.bgimage_normal]:self.color_normal;
    //    item.backgroundColor = bgColor;
}

- (CGFloat)getItemWidthForDefaultWidth:(CGFloat)default_width withTextSize:(CGSize)text_size
{
    CGFloat item_horizol_margin = self.item_horizon_margin;
    return ((text_size.width + item_horizol_margin * 2) >= default_width) ? (text_size.width + item_horizol_margin * 2) : default_width;
}

- (void)setBackgroundImage:(UIImage*)bg_image inFrame:(CGRect)bg_frame
{
    UIView *bg_view = _ALLOC_OBJ_WITHFRAME_(UIView, bg_frame);
    [bg_view setBackgroundColor:[UIColor colorWithPatternImage:bg_image]];
    [self insertSubview:bg_view atIndex:0];
    RELEASE_SAFELY(bg_view);
}

#pragma mark -- SignImageLayout
- (void)signImageLayout:(NSMutableArray*)dataSource
{
    //topline
    CGFloat line_height = 1.0f;
    CGFloat line_orginX = 0;
    CGFloat line_width  = self.frame.size.width;
    CGFloat line_orginY = 0;
    CGRect line_frame = CGRectMake(line_orginX, line_orginY, line_width, line_height);
    UILabel *lab_top_line = _ALLOC_OBJ_WITHFRAME_(UILabel, line_frame);
    [lab_top_line setBackgroundColor:[UIColor colorWithRed:224.0f/255.0f green:224.0f/255.0f blue:224.0f/255.0f alpha:1.0]];
    [self addSubview:lab_top_line];
    SIMPLE_SAFERELEASE(lab_top_line);
    
    
    //bottomline
    CGFloat bottom_line_height = 1.0f;
    CGFloat bottom_line_orginX = 0;
    CGFloat bottom_line_width  = self.frame.size.width;
    CGFloat bottom_line_orginY = self.frame.size.height - line_height;
    CGRect bottom_line_frame = CGRectMake(bottom_line_orginX, bottom_line_orginY, bottom_line_width, bottom_line_height);
    UILabel *lab_bottom_line = _ALLOC_OBJ_WITHFRAME_(UILabel, bottom_line_frame);
    [lab_bottom_line setBackgroundColor:[UIColor colorWithRed:224.0f/255.0f green:224.0f/255.0f blue:224.0f/255.0f alpha:1.0]];
    [self addSubview:lab_bottom_line];
    SIMPLE_SAFERELEASE(lab_bottom_line);
    
    if(!dataSource || [dataSource count]<=0)
        return;
    
    [self initNoteImageSign];
    
    NSInteger ndataCount = [dataSource count];
    
    //计算每个tabItem的frame
    CGFloat totalWidth = self.frame.size.width;
    CGFloat item_width = 0;
    if(self.isCoverage)
        item_width = (totalWidth - _itemSpace*(ndataCount + 1))/ndataCount;
    else
        item_width = self.itemWidth;
    
    CGFloat item_orginY = _padding_top;
    CGFloat item_height = self.frame.size.height - item_orginY*2;
    CGFloat content_width = 0;
    CGFloat item_orginX = _itemSpace;
    CustomTabItem *tmpSelectedItem = nil;
    for (NSInteger i=0; i<ndataCount; ++i)
    {
        CustomTabItem_DataItem *data_item = [dataSource objectAtIndex:i];
        NSString* str_title = [self getTitleForItem:data_item];
        CGSize text_size = [str_title sizeWithFont:FONT_TITLE(_font_size)];
        
        if(_font_size == 0)
            _font_size = 12.0;
        
        //获取最终item高度
        CGFloat twidth = [self getItemWidthForDefaultWidth:item_width withTextSize:text_size];
        
        CGRect item_frame   = CGRectMake(item_orginX, item_orginY, twidth, item_height);
        CustomTabItem* item = _ALLOC_OBJ_WITHFRAME_(CustomTabItem, item_frame);
        item.item_horizon_margin = self.item_horizon_margin;
        
        item.tabItem_delegate = self;
        if(_bgimage_normal)//背景图片优先级高于背景色
        {
            //            item.background.image = _bgimage_normal;
            [self setItemNormal:item withPaddingBottom:_padding_bottom];
        }
        
        //设置颜色
        if(!_bgimage_normal && _color_normal)
            item.color_normal = self.color_normal;
        if(!_bgimage_selected && _color_selected)
            item.color_selected = self.color_selected;
        if(_color_textNormal)
            item.color_textNormal = _color_textNormal;
        if(_color_textSelected)
            item.color_textSelected = _color_textSelected;
        
        [item setFontSize:_font_size];
        
        [item setIndex:i];
        [_view_scroll addSubview:item];
        SIMPLE_SAFERELEASE(item);
        
        
        //设置标题
        if(str_title)
            [item setTabItemTitle:str_title];
        
        //设置默认选中项
        if(i == _ndefaultSelectedIndex)
        {
            if(![str_title isEqualToString:@"默认"])
            {
                [self setItemSelected:item];
            }
            [item changeForState:TABITEM_STATE_SELECTED];
            
            tmpSelectedItem = [item retain];
            
            if(_isNeedDefaultSelectedEvent)
                [self toNextResponderWithObject:item];
        }
        else
            [item changeForState:TABITEM_STATE_NORMAL];
        
        //添加到容器中
        [_container addObject:item];
        
        item_orginX += (twidth + _itemSpace);
        
        content_width += (twidth + _itemSpace);
    }
    _ncurrentSelectedIndex = _ndefaultSelectedIndex;
    content_width += _itemSpace;
    _view_scroll.contentSize = CGSizeMake(content_width, _view_scroll.frame.size.height);
    [self setSignImageCenterForItem:tmpSelectedItem];
    RELEASE_SAFELY(tmpSelectedItem);
}

- (void)setSignImageCenterForItem:(CustomTabItem*)item
{
    [self setSignImageCenterForItem:item animal:NO];
}

- (void)setSignImageCenterForItem:(CustomTabItem*)item animal:(BOOL)animal
{
    [self initImageSign];
    if(animal)
    {
        _ANIMATIONS_INIT_BEGIN_(0.3);
        _imageSign.center = CGPointMake(item.center.x, item.frame.size.height - _imageSign.frame.size.height + 10);
        _ANIMATIONS_INIT_END_;
    }
    else
    {
        _imageSign.center = CGPointMake(item.center.x, item.frame.size.height - _imageSign.frame.size.height + 10);
    }

    CGFloat OffSetX = item.center.x + item.frame.size.width/2 - _view_scroll.frame.size.width;
    OffSetX = (OffSetX <= 0)?0:OffSetX;
    if(OffSetX <= 0)
    {
        OffSetX = 0;
        if((_view_scroll.contentSize.width - _itemSpace) > _view_scroll.frame.size.width)
            [self setNoteImageSignForNoteType:NOTE_TYPE_RIGHT];
    }
//    _view_scroll.contentOffset = CGPointMake(OffSetX, 0);
    [_view_scroll setContentOffset:CGPointMake(OffSetX, 0) animated:YES];
    [_view_scroll bringSubviewToFront:_imageSign];
}

/**
 descrtion:判断索引是否有效
 @parm: _index:用于判断的索引
 @returns: 有效则返回YES,否则返回NO
 add by zt 2013-4-3
 @exception:
 */
-(BOOL)isValidIndex:(NSInteger)index
{
    BOOL result = NO;
    
    if(!_container)
        result = NO;
    else
    {
        if(index < 0)
            result = NO;
        else if(index > [_container count])
            result = NO;
        else
            result = YES;
    }
    
    return result;
}

/**
 descrtion:根据索引获取对应的item
 @parm: _index:目标item所在的索引
 @returns: 返回找到的item，如果没找到返回nil,调用时候需对结果进行非空判断
 add by zt 2013-4-3
 @exception:
 */
-(CustomTabItem*)tabItemAtIndex:(NSInteger)index
{
    BOOL isValidIndex = [self isValidIndex:index];
    
    if(isValidIndex)
        return [_container objectAtIndex:index];
    
    return nil;
}

#pragma mark -- TabItem
/**
 descrtion:根据索引获取对应的item的title
 @parm: _index:目标item所在的索引
 @returns: 返回找到的item的title，如果没找到返回@""
 add by zt 2013-4-3
 @exception:
 */
- (NSString*)titleAtIndex:(NSInteger)index
{
    
    CustomTabItem* item = [self tabItemAtIndex:index];
    
    if(!item)
        return @"";
    else
        return [item title];
}

/**
 descrtion:根据索引设置对应的字体大小
 @parm: _index:目标item所在的索引 font_size:字体大小
 @returns:
 add by zt 2013-4-3
 @exception:
 */
- (void)setFontSizeAtIndex:(NSInteger)index font_size:(CGFloat)font_size
{
    CustomTabItem* item = [self tabItemAtIndex:index];
    
    if(!item)
        return;
    else
        return [item setFontSize:font_size];
}

/**
 descrtion:根据索引设置对应的对齐方式
 @parm: _index:目标item所在的索引 _align:对齐方式
 @returns:
 add by zt 2013-4-3
 @exception:
 */
- (void)setAlignAtiIndex:(NSInteger)index align:(NSUITextAlignment)align
{
    CustomTabItem* item = [self tabItemAtIndex:index];
    
    if(!item)
        return;
    else
        return [item setAlign:align];
}

#pragma mark -- observe
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqualToString:@"dataSource"])
    {
        [self setNeedsDisplay];
        return;
    }
}

/**
 descrtion:事件交给下个处理者
 @parm: parm:这里传递对应的item
 @returns:
 add by zt 2013-4-7
 @exception:
 */
- (void)toNextResponderWithObject:(id)parm
{//交给上层视图或者控制器处理
    if(_delegate && [_delegate respondsToSelector:@selector(doTabItemClick:withItem:)])
        [_delegate performSelector:@selector(doTabItemClick:withItem:) withObject:self withObject:parm];
}

#pragma mark -- TabItemDelegate
- (void)doTabItemClick:(id)sender
{
    CustomTabItem* cur_item = (CustomTabItem*)sender;
    if(cur_item)
    {
        _ncurrentSelectedIndex = cur_item.nindex;
        if(self.bgimage_selected)
        {
            [self setItemSelected:cur_item];
        }
        [cur_item changeForState:TABITEM_STATE_SELECTED];
        if(_layout_type == LAYOUT_TYPE_SIGNIMAGE)
        {
            [self setSignImageCenterForItem:cur_item animal:_changeAnimal];
        }
    }
    for(CustomTabItem* item in _container)
    {
        if(item == cur_item)
            continue;
        if(self.bgimage_normal)
        {
            [self setItemNormal:item withPaddingBottom:_padding_bottom];
        }
        else
            item.background.image = nil;
        [item changeForState:TABITEM_STATE_NORMAL];
    }
    
    [self toNextResponderWithObject:cur_item];
}

//判断位置是否到最右侧
- (BOOL)isBigestOffset:(CGPoint)offset
{
    if (offset.x >= (_view_scroll.contentSize.width - _itemSpace) - _view_scroll.frame.size.width ||
        _view_scroll.contentSize.width < _view_scroll.frame.size.width)
        return YES;
    return NO;
}

#pragma mark -- UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGSize content_size = scrollView.contentSize;
    if(content_size.width > scrollView.frame.size.width)
    {//显示箭头
        CGPoint offset = _view_scroll.contentOffset;
        BOOL isBigestOffset = [self isBigestOffset:offset];
        if (isBigestOffset)
        {//滑到最右边
            [self setNoteImageSignForNoteType:NOTE_TYPE_LEFT];
        }
        else
        {
            [self setNoteImageSignForNoteType:NOTE_TYPE_RIGHT];
        }
    }
}

@end






